package com.boot.config;

import com.boot.pojo.User;
import com.boot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

//自定义的 Realm  ,继承AuthorizingRealm即可
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权 doGetAuthorizationInfo");
        //给用户授予权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录得这个对象
        Subject subjcet = SecurityUtils.getSubject();
        //拿到User对象
        String currentUser = (String) subjcet.getPrincipal(); //从认证方法中 return SimpleAuthenticationInfo(第一个参数) 拿到得当前用户对象

        Set<String> menuNameSet =  new HashSet<>();
        menuNameSet.add("/user/update");
        menuNameSet.add("/user/select");
        menuNameSet.add("/user/delete");
        info.addRole("common");
        info.addStringPermissions(menuNameSet);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证 doGetAuthenticationInfo");
        //用户名，密码 数据库中取

        String userToken = (String)authenticationToken.getPrincipal();
        //连接数据库  执行
        User user = userService.queryUserByName(userToken);  //idea:Ctrl+Alt+B查看实现类方法

        if(user==null){ //没有这个用户
            return null;//返回null 就会抛出异常 UnknownAccountException 用户名不存在
        }
        System.out.println();
        System.out.println();
        System.out.println(user);
        System.out.println();
        System.out.println();
        return new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
    }
}
